﻿using McsWeb.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using FangChan.Common;
using Web.Filters;
using McsWeb.Common;

namespace McsWeb.Controllers
{
    [GlobalAuthorization]
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var cookies = Web.Common.CookiesManagement.GetCookies();
            var ticket = Web.Common.CookiesManagement.GetTicket(cookies);
            var model = Web.Common.CookiesManagement.GetLoginModel(ticket);
            ViewBag.UserName = model.UserName;
            return View();
        }

        [AllowAnonymous]
        public ActionResult UserLogin()
        {
            FormsAuthentication.SignOut();
            return View();
        }

        [AllowAnonymous]
        public ActionResult LoginAsync(string name, string pass, int remember)
        {
            if (Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.GetSingle("select count(*) from Staffs where LoginName='" + name + "'")) != 1)
            {
                return Json(new Result<string>() { Content = "无些登录名", Data = (new LoginModel()).ToJson(), TotalRows = 0, Type = AjaxResultType.Error });
            }
            string LoginPass = FangChan.DBUtility.DbHelperSQL.GetSingle("select LoginPass from Staffs where LoginName='" + name + "'").ToString();
            if (LoginPass != pass)
            {
                return Json(new Result<string>() { Content = "密码错误", Data = (new LoginModel()).ToJson(), TotalRows = 0, Type = AjaxResultType.Error });
            }
            //if (Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.GetSingle("  select count(*) from Users where LoginName='" + name + "' and (select count(*) from UserRoles where UserID=Users.ID and RoleID in(1,2))>0")) == 0)
            //{
            //    return Json(new Result<string>() { Content = "没有登录权限", Data = (new LoginModel()).ToJson(), TotalRows = 0, Type = AjaxResultType.Error });
            //}
            LoginModel lm = new LoginModel() { UserID = Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.GetSingle("select ID from Staffs where LoginName='" + name + "'")), UserName = Convert.ToString(FangChan.DBUtility.DbHelperSQL.GetSingle("select Name from Staffs  where LoginName='" + name + "'")), LoginName = name };
            string data = lm.ToJson();
            var ticket = new FormsAuthenticationTicket(
                                1,
                                name,
                                DateTime.Now,
                                DateTime.Now.Add(FormsAuthentication.Timeout),
                                remember == 1 ? true : false,
                                data);
            var cookie = new HttpCookie(
                FormsAuthentication.FormsCookieName,
                FormsAuthentication.Encrypt(ticket));
            cookie.HttpOnly = true;
            Response.Cookies.Add(cookie);

            return Json(new Result<LoginModel>() { Content = "成功", Data = lm, TotalRows = 0, Type = AjaxResultType.Success });
        }

        [AllowAnonymous]
        public string Login(string LoginName, string LoginPass)
        {
            var data = Login(1, LoginName, LoginPass);
            if (data.success)
            {
                return "1";
            }
            else
            {
                return "0";
            }
            //return TomNet.Utility.Data.JsonHelper.ToJson(data);
        }
        [AllowAnonymous]
        public string Reg(string LoginName = "", string LoginPass = "", int SMSCode = 0, string Name = "", int Sex = 1, string CardID = "", string PassQuestion1 = "", string PassAnswer1 = "", string PassQuestion2 = "", string PassAnswer2 = "", string PassQuestion3 = "", string PassAnswer3 = "")
        {
            var data = Login(4, LoginName, LoginPass, SMSCode, Name, Sex, CardID, PassQuestion1, PassAnswer1, PassQuestion2, PassAnswer2, PassQuestion3, PassAnswer3);
            //if (data.success)
            //{
            //    return "1";
            //}
            //else
            //{
            //    return "0";
            //}
            return TomNet.Utility.Data.JsonHelper.ToJson(data);
        }
        [AllowAnonymous]
        public string GetRegSMSCode(string LoginName = "")
        {
            var data = Login(2, LoginName);

            //if (data.success)
            //{
            //    return "1";
            //}
            //else
            //{
            //    return "0";
            //}
            return TomNet.Utility.Data.JsonHelper.ToJson(data);
        }
        [AllowAnonymous]
        public string GetNodeServerList(int v)
        {
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select ID,IP,Port from NodeServers where State=1").Tables[0];
            List<string> l = new List<string>();
            foreach (DataRow item in dt.Rows)
            {
                l.Add(Convert.ToString(item["IP"]) + ":" + Convert.ToString(item["Port"]));
            }
            ClientVersion m = new ClientVersion();
            m.NodeSvr = l;
            m.Url = FangChan.DBUtility.DbHelperSQL.GetSingle("select value from options where id=" + (v == 0 ? "4" : (v == 1 ? "5" : "6"))).ToString();
            m.Ver = FangChan.DBUtility.DbHelperSQL.GetSingle("select value from options where id = " + (v == 0 ? "1" : (v == 1 ? "2" : "3"))).ToString();
            return TomNet.Utility.Data.JsonHelper.ToJson(m);
        }
        private ResultModel Login(int Type, string LoginName = "", string LoginPass = "", int SMSCode = 0, string Name = "", int Sex = 1, string CardID = "", string PassQuestion1 = "", string PassAnswer1 = "", string PassQuestion2 = "", string PassAnswer2 = "", string PassQuestion3 = "", string PassAnswer3 = "")
        {
            ResultModel rm = new ResultModel();
            rm.success = false;
            rm.message = "失败";
            SqlParameter[] parameters = {
                                            new SqlParameter("@LoginName",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@LoginPass",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@SMSCode",SqlDbType.Int),
                                            new SqlParameter("@Name",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@Sex",SqlDbType.Int),
                                            new SqlParameter("@CardID",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@PassQuestion1",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@PassAnswer1",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@PassQuestion2",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@PassAnswer2",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@PassQuestion3",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@PassAnswer3",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@Type",SqlDbType.Int),
                                            new SqlParameter("@str",SqlDbType.NVarChar,40000),
                                            new SqlParameter("@ReturnValue",SqlDbType.Int)};
            parameters[0].Value = LoginName;
            parameters[1].Value = LoginPass;
            parameters[2].Value = SMSCode;
            parameters[3].Value = Name;
            parameters[4].Value = Sex;
            parameters[5].Value = CardID;
            parameters[6].Value = PassQuestion1;
            parameters[7].Value = PassAnswer1;
            parameters[8].Value = PassQuestion2;
            parameters[9].Value = PassAnswer2;
            parameters[10].Value = PassQuestion3;
            parameters[11].Value = PassAnswer3;
            parameters[12].Value = Type;
            parameters[13].Direction = ParameterDirection.Output;
            parameters[14].Direction = ParameterDirection.ReturnValue;
            DataSet ds = FangChan.DBUtility.DbHelperSQL.RunProcedure("Sp_LoginRequest", parameters, "aaa", 3000);
            rm.message = parameters[13].Value.ToString();
            if (Convert.ToInt32(parameters[14].Value) == 1)
            {
                rm.success = true;
                switch (Type)
                {
                    case 2:
                    case 3:
                        System.Threading.Tasks.Task task1 = new System.Threading.Tasks.Task(() => SendMessage.SendMessgeYanZhengMa(LoginName, Convert.ToInt32(ds.Tables[0].Rows[0]["SMSCode"]).ToString("000000")));
                        task1.Start();
                        rm.message = "短信发送成功";
                        break;
                    case 4:
                    case 5:
                        break;
                    default:
                        break;
                }
            }
            return rm;
        }
        public ActionResult UsersList()
        {
            return View();
        }
        public string UsersListAsync(string Name, int pageIndex, int pageSize)
        {
            if (string.IsNullOrEmpty(Name))
            {
                Name = "";
            }
            var cookies = Web.Common.CookiesManagement.GetCookies();
            var ticket = Web.Common.CookiesManagement.GetTicket(cookies);
            var model = Web.Common.CookiesManagement.GetLoginModel(ticket);
            List<UsersModel> l = new List<UsersModel>();
            int total = Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.GetSingle("select dbo.Fn_Value_UsersNumber(" + model.UserID + ",'" + Name + "')"));
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select * from dbo.Fn_Table_UsersList(" + model.UserID + ",'" + Name + "'," + pageIndex + "," + pageSize + ")").Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                UsersModel m = new UsersModel();
                m.ID = Convert.ToInt32(item["ID"]);
                m.UserName = Convert.ToString(item["UserName"]);
                m.Phone = Convert.ToString(item["Phone"]);
                m.Sex = Convert.ToString(item["Sex"]);
                m.WeiXin = Convert.ToString(item["PassQuestion2"]);
                m.CardID = Convert.ToString(item["CardID"]);
                m.MinerNumber = Convert.ToInt32(item["MinerNumber"]);
                m.OnLineNumber = Convert.ToInt32(item["OnLineNumber"]);
                m.DigNumber = Convert.ToInt32(item["DigNumber"]);
                m.StaffName = Convert.ToString(item["StaffName"]);
                l.Add(m);
            }
            DataTable fdt = FangChan.DBUtility.DbHelperSQL.Query("select * from dbo.Fn_Table_UsersListFooter(" + model.UserID + ",'" + Name + "')").Tables[0];
            int TotalMinerNumber = Convert.ToInt32(fdt.Rows[0]["TotalMinerNumber"]);
            int TotalOnLineNumber = Convert.ToInt32(fdt.Rows[0]["TotalOnLineNumber"]);
            int TotalDigNumber = Convert.ToInt32(fdt.Rows[0]["TotalDigNumber"]);

            GridData<UsersModel> gridData = total > 0 ? new GridData<UsersModel>() { total = total, rows = l, TotalMinerNumber = TotalMinerNumber, TotalOnLineNumber = TotalOnLineNumber, TotalDigNumber = TotalDigNumber } : new GridData<UsersModel>() { total = total, rows = new List<UsersModel>() };

            return gridData.ToJson();
        }

        public ActionResult UsersUpdate(int id)
        {
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select * from Users where id=" + id).Tables[0];

            UsersModel Users = new UsersModel();

            Users.ID = Convert.ToInt32(dt.Rows[0]["ID"]);
            Users.StaffID = Convert.ToInt32(dt.Rows[0]["StaffID"]);

            ViewBag.users = Users;


            return View();
        }
        public ActionResult UsersUpdateAsync(UsersModel Users)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();


            string sql = "update Users set StaffID='" + Users.StaffID + "' where ID=" + Users.ID;

            int count = Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.ExecuteSql(sql));

            if (count > 0)
            {
                result.Type = AjaxResultType1.Success;
                result.Content = "修改成功";
            }
            else
            {
                result.Type = AjaxResultType1.Error;
                result.Content = "修改失败";
            }
            return JsonEx(result);
        }

        public string GetStaffId()
        {
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select ID,Name from Staffs").Tables[0];

            return dt.DataTable2Json();
        }

        public ActionResult MinersList(int UserID = 0, int State = -1)
        {
            ViewBag.UserID = UserID;
            ViewBag.State = State;
            return View();
        }
        public string MinersListAsync(int UserID = 0, int State = -1, string Name = "", int pageIndex = 1, int pageSize = 20)
        {
            var cookies = Web.Common.CookiesManagement.GetCookies();
            var ticket = Web.Common.CookiesManagement.GetTicket(cookies);
            var model = Web.Common.CookiesManagement.GetLoginModel(ticket);
            List<MinersModel> l = new List<MinersModel>();
            int total = Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.GetSingle("select dbo.Fn_Value_BackMinersCount(" + model.UserID + "," + UserID + "," + State + ",'" + Name + "')"));
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select * from dbo.Fn_Table_BackMiners(" + model.UserID + "," + UserID + "," + State + ",'" + Name + "'," + pageIndex + "," + pageSize + ")").Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                MinersModel m = new MinersModel();
                m.AdvParams = Convert.ToString(item["AdvParams"]);
                m.AutoName = Convert.ToBoolean(item["AutoName"]);
                m.AutoRun = Convert.ToBoolean(item["AutoRun"]);
                m.AutoUpdate = Convert.ToBoolean(item["AutoUpdate"]);
                m.BackupPool = Convert.ToString(item["BackupPool"]);
                m.CoreType = (CoreType)Convert.ToInt32(item["CoreType"]);
                m.Dcri = Convert.ToString(item["Dcri"]);
                m.Eres = Convert.ToString(item["Eres"]);
                m.FirstCoin = Convert.ToString(item["FirstCoin"]);
                m.FirstPool = Convert.ToString(item["FirstPool"]);
                m.FirstWallet = Convert.ToString(item["FirstWallet"]);
                m.HighTempStrategy = (HighTempStrategy)Convert.ToInt32(item["HighTempStrategy"]);
                m.HighTempWarn = Convert.ToBoolean(item["HighTempWarn"]);
                m.ID = Convert.ToInt32(item["ID"]);
                m.LowStrengthWarn = Convert.ToBoolean(item["LowStrengthWarn"]);
                m.MacAddress = Convert.ToString(item["MacAddress"]);
                m.MaxFan = Convert.ToString(item["MaxFan"]);
                m.MaxTemp = Convert.ToString(item["MaxTemp"]);
                m.MinerName = Convert.ToString(item["MinerName"]);
                m.MinFan = Convert.ToString(item["MinFan"]);
                m.MinSpeed = Convert.ToString(item["MinSpeed"]);
                m.MinTemp = Convert.ToString(item["MinTemp"]);
                m.Second = Convert.ToBoolean(item["Second"]);
                m.SecondCoin = Convert.ToString(item["SecondCoin"]);
                m.SecondPool = Convert.ToString(item["SecondPool"]);
                m.SecondWallet = Convert.ToString(item["SecondWallet"]);
                m.State = Convert.ToInt32(item["State"]);
                m.StateTime = Convert.ToDateTime(item["StateTime"]);
                m.UserID = Convert.ToInt32(item["UserID"]);
                m.UserName = Convert.ToString(item["UserName"]);
                l.Add(m);
            }
            GridData<MinersModel> gridData = total > 0 ? new GridData<MinersModel>() { total = total, rows = l } : new GridData<MinersModel>() { total = total, rows = new List<MinersModel>() };

            return gridData.ToJson();
        }
        public string MinersStateAsync()
        {
            TomNet.Redis.RedisClient redisClient = new TomNet.Redis.RedisClient();
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select ID from Miners where State=0").Tables[0];
            int i = 0;
            foreach (DataRow item in dt.Rows)
            {
                int MinersID = Convert.ToInt32(item["ID"]);
                if (redisClient.KeyExists(MinersID.ToString()))
                {
                    FangChan.DBUtility.DbHelperSQL.ExecuteSql("update Miners set State=2 where ID=" + MinersID.ToString());
                    i = i + 1;
                }
            }
            return i.ToString() + ":OK";
        }
    }
}